< previous page page_169 next page >

Page 169
To create a variable that retains its value, you use the Static keyword in the variable declaration. It tells Visual Basic that the variable can be referenced only within the procedure but to remember the value because it might be needed again. Here's an example of a variable declared using the Static keyword:
Static nPageNumber As Integer
note.gif If you use the Static keyword in front of a Function or Sub header (such as Static Sub MySub(), all variables in that procedure are treated as static. The following example subroutine demonstrates this concept:
Static Sub Test()
       Dim x As Integer
       Debug.Print "Value of x before assignment statement = " & x
       x = 1234
       Debug.Print "Value of x after assignment statement = " & x
End Sub
In this example, the variable x would be treated as a static variable. The first time you called the Test function, the output would be 0 and 1234. The next call would print 1234 for both the before and after values. square.gif

Using the Option Explicit Statement
Earlier, in the section "Variable Declarations," you learned that declaring your program's variables before they are used is good programming practice. You can have Visual Basic "force" you to declare variables by setting one of its environment options. To do so, access Visual Basic's Options dialog box by choosing Tools, Options. On this dialog box's Editor tab is the Require Variable Declaration option (see Figure 8.1). Selecting this box requires you to declare each variable before you use it.
0169-01.jpg
Figure 8.1
The Require Variable Declaration option helps
prevent you from mistyping variable names.
Setting the Require Variable Declaration option causes the Option Explicit statement to be placed in the General Declarations section of all new modules and forms that are added to your project, as shown in Figure 8.2.

 
< previous page page_169 next page >